package com.itheima.consumer.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j

@Configuration
public class ErrorMessageConfiguration {


    //声明一个Direct类型的交换机，用于处理错误消息
    @Bean
    public DirectExchange errorExchange() {
        return new DirectExchange("error.direct");
    }

    //声明一个队列，用于接收错误消息
    @Bean
    public Queue errorQueue() {
        return new Queue("error.queue");
    }

    //将错误队列绑定到错误交换机，并指定路由键为"error"
    @Bean
    public Binding errorBinding() {
        return BindingBuilder.bind(errorQueue()).to(errorExchange()).with("error");//with:routingKey
    }

    /**
     * 设置失败策略
     *
     * @param rabbitTemplate
     * @return
     */
     //将失败的信息传给指定的交换机
    @Bean
    public MessageRecoverer errorMessageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", "error");
    }

}
